package mspbots.cw.client.core.data.subdata;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.client.core.AbstractToolsUtil;
import mspbots.cw.client.core.data.BaseSyncService;
import mspbots.cw.client.core.app.SyncRequest;
import mspbots.cw.client.core.client.ClientProperties;
import mspbots.cw.common.*;
import mspbots.cw.common.subdata.SubDataType;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @author Jay.Yang
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class OpportunitiesServiceImpl extends AbstractToolsUtil implements BaseSyncService {

    private Flux<JsonNode> get(ClientProperties properties, QueryParams queryParams) {
        return this.cwWebClient.fetch("/sales/opportunities", queryParams)
                .contextWrite(ctx -> ctx.put("properties", properties));
    }

    @Override
    public Mono<Void> syncSlow(ClientProperties properties) {
        ResultSync resultSync = ResultSync.withDefault("OPPORTUNITIES-SYNC");
        return super.readAnchorTimeLong(RedisKeys.OPPORTUNITIES_ANCHOR_REDIS_KEY_PREFIX + properties.getTenantId())
                .map(syncTime -> QueryParams.withDefault()
                        .setConditions("lastUpdated >[" + syncTime.format(DateTimeFormatter.ISO_DATE_TIME) + "]"))
                .flatMapMany(params -> this.get(properties, params))
                .contextWrite(ctx -> ctx.put("resultSync", resultSync))
                .doOnNext(companyNode -> this.syncResult(properties.getTenantId(),
                        resultSync.getRequestId(), companyNode))
                .then();
    }

    private void syncResult(Long tenantId, UUID id, JsonNode resultNode) {
        this.sendEntity(RabbitKeys.SUB_DATA_SYNC_QUEUE_KEY, ResultMsg.builder()
                .requestId(id).id(resultNode.get("id").longValue())
                .action(SubDataType.OPPORTUNITIES.name()).entity(resultNode).tenantId(tenantId)
                .syncDate(LocalDateTime.now()).build());

        this.recordAnchorTimeLong(RedisKeys.OPPORTUNITIES_ANCHOR_REDIS_KEY_PREFIX + tenantId,
                resultNode.findValue("lastUpdated").textValue());
    }

    @Override
    public Mono<Void> manualSync(ClientProperties properties, SyncRequest syncRequest) {
        ResultSync resultSync = ResultSync.withDefault("MANUAL-OPPORTUNITIES-SYNC");
        String conditionsStr = "lastUpdated>=[" + syncRequest.getBeginTime().format(DateTimeFormatter.ISO_DATE_TIME) +
                "] and lastUpdated <=[" + syncRequest.getEndTime().format(DateTimeFormatter.ISO_DATE_TIME) + "]";
        return this.get(properties, QueryParams.withDefault().setConditions(conditionsStr)
                .setOrderBy("lastUpdated asc"))
                .contextWrite(ctx -> ctx.put("resultSync", resultSync))
                .doOnNext(node -> this.syncResult(properties.getTenantId(),
                        resultSync.getRequestId(), node))
                .then();
    }

}
